package com.first.agent.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.first.agent.common.R;
import com.first.agent.service.UserService;
import com.first.agent.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/*
登录功能
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         //1.验证码验证
        //获取输入框中的验证码
        String vercode = request.getParameter("vercode");
        //获取服务器session域中存储的验证码
        String serverVerCode = request.getSession().getAttribute("serverVerCode").toString();
        //2.比对
        R r = new R();
        if(!serverVerCode.equalsIgnoreCase(vercode)){
            //不一致
            r.setCode(401);
            r.setMsg("验证码错误");
        }else {
            //一致
            //开始验证用户名和密码
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            //调用service,service调用dao
            UserService userService = new UserServiceImpl();
            r = userService.login(username,password);
        }
        //3.响应
        //响应回来数据格式和编码
            response.setContentType("application/json;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.write(JSONObject.toJSONString(r));
            pw.flush();
            pw.close();

    }
}
